package com.mine.modules.sys.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mine.common.constant.CommonConstant;
import com.mine.common.domain.query.PageQuery;
import com.mine.common.domain.vo.Result;
import com.mine.common.utils.oConvertUtils;
import com.mine.modules.sys.entity.SysDict;
import com.mine.modules.sys.service.ISysDictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-10-09
 */
@Api(tags = "数据字典管理")
@RestController
@RequestMapping("/sys/dict")
@RequiredArgsConstructor
public class SysDictController {

    private final ISysDictService sysDictService;

    @ApiOperation(value = "通过字典编码查询")
    @RequestMapping(value = "/queryByCode", method = RequestMethod.GET)
    public Result<?> queryByCode(@RequestParam(name = "code") String code) {
        return sysDictService.getDictByCode(code);
    }

    @ApiOperation(value = "字典列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<IPage<SysDict>> queryPageList(PageQuery pageQuery) {
        Result<IPage<SysDict>> result = new Result<IPage<SysDict>>();
        LambdaQueryWrapper<SysDict> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(pageQuery.getKeywords())) {
            queryWrapper.and(e -> e
                    .like(SysDict::getDictName, pageQuery.getKeywords())
                    .or()
                    .like(SysDict::getDictCode, pageQuery.getKeywords())
            );
        }
        Page<SysDict> page = new Page<SysDict>(pageQuery.getPageNo(), pageQuery.getPageSize());
        IPage<SysDict> pageList = sysDictService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @ApiOperation(value = "添加或修改字典")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result<?> addOrEdit(SysDict sysDict) {
        try {
            if (sysDict == null || StringUtils.isBlank(sysDict.getDictCode())) {
                return Result.error("参数不完整！");
            }
            if (StringUtils.isEmpty(sysDict.getId())) {
                SysDict oldDict = sysDictService.lambdaQuery().eq(SysDict::getDictCode,sysDict.getDictCode()).one();
                if(oldDict!=null){
                    return Result.error("该值已存在！");
                }
                sysDict.setCreateTime(new Date());
                sysDict.setDelFlag(CommonConstant.DEL_FLAG_0);
                sysDictService.save(sysDict);
            } else {
                SysDict oldSysDict = sysDictService.getById(sysDict.getId());
                if (oldSysDict == null) {
                    return Result.error("数据不存在，请刷新重试！");
                }
                oldSysDict = BeanUtil.toBean(sysDict, SysDict.class);
                sysDictService.updateById(oldSysDict);
            }
            return Result.ok("保存成功！");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation(value = "删除字典")
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Result<SysDict> delete(@RequestParam(name = "id", required = true) String id) {
        Result<SysDict> result = new Result<SysDict>();
        boolean ok = sysDictService.removeById(id);
        if (ok) {
            result.success("删除成功!");
        } else {
            result.error500("删除失败!");
        }
        return result;
    }

    @ApiOperation(value = "批量删除字典")
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Result<SysDict> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<SysDict> result = new Result<SysDict>();
        if (oConvertUtils.isEmpty(ids)) {
            result.error500("参数不识别！");
        } else {
            sysDictService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

}
